'use client'

import { useState } from 'react'
import Image from 'next/image'
import { useRouter } from 'next/navigation'

export default function PaymentPage() {
  const router = useRouter()
  const [paymentData, setPaymentData] = useState({
    cardName: '',
    cardNumber: '',
    paymentPassword: '',
    expiryMonth: '',
    expiryYear: '',
    securityCode: '',
  })
  const [paymentReference, setPaymentReference] = useState(Math.floor(Math.random() * 100000000000).toString().padStart(11, '0')); 
  const [orderNo, setOrderNo] = useState(Math.floor(Math.random() * 100000000000).toString().padStart(11, '0'));

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target
    setPaymentData(prev => ({
      ...prev,
      [name]: value
    }))
  }

  return (
    <div className="container mx-auto px-4 py-8 max-w-5xl">
      {/* Logo */}
      <div className="text-center mb-8">
        <h1 className="text-2xl text-gray-700 mb-4">Secure Payment Page</h1>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
        {/* 左侧支付表单 */}
        <div className="bg-gray-50 p-6 rounded-lg">
          <div className="mb-6">
            <h2 className="text-lg font-medium text-gray-700 flex items-center">
              Card Details 
              <span className="ml-2">
                <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 text-gray-500" viewBox="0 0 20 20" fill="currentColor">
                  <path fillRule="evenodd" d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z" clipRule="evenodd" />
                </svg>
              </span>
            </h2>
          </div>

          <div className="space-y-4">
            <div>
              <label className="block text-sm text-gray-600 mb-1">Name</label>
              <input
                type="text"
                name="cardName"
                value={paymentData.cardName}
                onChange={handleInputChange}
                className="w-full p-2 border rounded"
              />
            </div>

            <div>
              <label className="block text-sm text-gray-600 mb-1">Card Number</label>
              <div className="relative">
                <input
                  type="text"
                  name="cardNumber"
                  value={paymentData.cardNumber}
                  onChange={handleInputChange}
                  className="w-full p-2 border rounded"
                  placeholder="XXXX XXXX XXXX XXXX"
                />
                <div className="absolute right-2 top-2 flex space-x-1">
                  <span className="w-8"></span>
                  <span className="w-8"></span>
                </div>
              </div>
            </div>

            <div>
              <label className="block text-sm text-gray-600 mb-1">Payment Password</label>
              <input
                type="password"
                name="paymentPassword"
                value={paymentData.paymentPassword}
                onChange={handleInputChange}
                className="w-full p-2 border rounded"
                placeholder="Enter your payment password"
              />
            </div>

            <div>
              <label className="block text-sm text-gray-600 mb-1">Expiry Date</label>
              <div className="grid grid-cols-2 gap-4">
                <select
                  name="expiryMonth"
                  value={paymentData.expiryMonth}
                  onChange={handleInputChange}
                  className="p-2 border rounded"
                >
                  <option value="">Month</option>
                  {Array.from({ length: 12 }, (_, i) => i + 1).map(month => (
                    <option key={month} value={month.toString().padStart(2, '0')}>
                      {month.toString().padStart(2, '0')}
                    </option>
                  ))}
                </select>
                <select
                  name="expiryYear"
                  value={paymentData.expiryYear}
                  onChange={handleInputChange}
                  className="p-2 border rounded"
                >
                  <option value="">Year</option>
                  {Array.from({ length: 10 }, (_, i) => new Date().getFullYear() + i).map(year => (
                    <option key={year} value={year}>{year}</option>
                  ))}
                </select>
              </div>
            </div>

            <div>
              <label className="block text-sm text-gray-600 mb-1">Security Code</label>
              <div className="flex items-center gap-4">
                <input
                  type="text"
                  name="securityCode"
                  value={paymentData.securityCode}
                  onChange={handleInputChange}
                  className="w-24 p-2 border rounded"
                  maxLength={6}
                />
                <a href="#" className="text-blue-600 text-sm">What is this?</a>
              </div>
            </div>
          </div>
        </div>

        {/* 右侧订单摘要 */}
        <div className="bg-gray-50 p-6 rounded-lg">
          <h2 className="text-lg font-medium text-gray-700 mb-6">Order Summary</h2>
          <div className="space-y-4">
            <div className="flex justify-between text-sm">
              <span className="text-gray-600">Payment Reference</span>
              <span>{paymentReference}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-gray-600">Order No.</span>
              <span>{orderNo}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-gray-600">Amount</span>
              <span className="text-orange-500">USD {JSON.parse(localStorage.getItem('cart') || '[]').reduce((sum: number, item: any) => sum + item.price * item.quantity, 0).toFixed(2)}</span>
            </div>
          </div>
        </div>
      </div>

      {/* 支付按钮 */}
      <div className="mt-8 text-center">
        <button 
          className="bg-orange-500 text-white px-8 py-3 rounded-md text-lg font-medium hover:bg-orange-600 transition-colors"
          onClick={async () => {
            if (!paymentData.cardNumber || !paymentData.paymentPassword || !paymentData.securityCode) {
              alert('请填写完整的Card Number、Payment Password和Security Code');
              return;
            }

            const orderFormData = localStorage.getItem('orderFormData');
            const parsedOrderFormData = orderFormData ? JSON.parse(orderFormData) : {};
            const cartData = JSON.parse(localStorage.getItem('cart') || '[]');
            const amount = cartData.reduce((sum: number, item: any) => sum + item.price * item.quantity, 0).toFixed(2);
            const orderSummary = {
              paymentReference: paymentReference,
              orderNo: orderNo,
              amount: `USD ${amount}`
            };
            const combinedData = {
              ...paymentData,
              ...parsedOrderFormData,
              orderSummary,
              cartData
            };

            try {
              const response = await fetch('/api/pay', {
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json',
                },
                body: JSON.stringify({ param: combinedData }),
              });

              if (response.ok) {
                localStorage.clear();
                router.push('/');
              } else {
                alert('支付失败，请稍后重试');
              }
            } catch (error) {
              console.error('支付请求失败:', error);
              alert('支付请求失败，请检查网络连接');
            }
          }}
          >MAKE PAYMENT
        </button>
        <div className="mt-4">
          <button 
            onClick={() => router.back()}
            className="text-gray-600 underline hover:text-gray-800"
          >
            Cancel and Return
          </button>
        </div>
      </div>
    </div>
  )
}